import { ConfigProvider, Form, Input, Select, Switch, TreeSelect } from 'antd';
import React, { useEffect, useMemo, useState } from 'react';

import './index.scss';

import { SHORT_TEXT } from '@/common/app/constants';
import { GetGroupTreeList, CreateUserReq, GetRoleRes } from '@/common/types';
import Modals from '@/components/modals/Modals.tsx';
import { useTiangongRole } from '@/hooks/useTiangongRole';
import { useInitializeData } from '@/store/configStore';

interface GroupUserForm extends CreateUserReq {
  id: string;
}

interface Props {
  open: boolean;
  onOk: (value: any, id?: string) => void;
  onCancel: () => void;
  treeData: GetGroupTreeList[];
  defaultValue?: GroupUserForm; // 默认值
  updateOrEdit: boolean;
  roleList: GetRoleRes[];
  confirmLoading: boolean;
  activeValue?: GetGroupTreeList;
  userSystemCode: string;
}

const UpdateModal = ({
  open = true,
  onOk,
  onCancel,
  treeData,
  updateOrEdit,
  defaultValue,
  roleList,
  confirmLoading,
  activeValue,
  userSystemCode,
}: Props) => {
  const [form] = Form.useForm();
  const [tree, setTree] = useState<GetGroupTreeList[]>([]);

  const { license_edition, allowLocalAccount } = useInitializeData();
  const isLocalAccount = useMemo(() => {
    if (!license_edition) {
      return false;
    }
    return !!allowLocalAccount;
  }, [allowLocalAccount, license_edition]);

  const { isTiangongManager } = useTiangongRole();

  useEffect(() => {
    if (form && defaultValue) {
      form.setFieldsValue(defaultValue);
    }
  }, [defaultValue]);

  useEffect(() => {
    if (treeData.length > 0) {
      let result = treeData[0].children;

      if (userSystemCode !== 'default') {
        result = result.filter((item) => item.system_code !== 'default');
      }
      setTree(result);
    }
  }, [activeValue, treeData, userSystemCode]);

  const onSubmit = () => {
    form.submit();
  };

  const onFinish = (values: any) => {
    onOk(values, defaultValue?.id);
  };

  return (
    <Modals
      title={updateOrEdit ? '新增用户' : '编辑用户信息'}
      open={open}
      onOk={onSubmit}
      onCancel={onCancel}
      confirmLoading={confirmLoading}
    >
      <ConfigProvider
        theme={{
          components: {
            Form: {
              labelColor: '#474C5F',
            },
          },
        }}
      >
        <Form layout="vertical" onFinish={onFinish} form={form}>
          <Form.Item
            label={isTiangongManager ? '邮箱' : '名称'}
            name="name"
            rules={[
              { required: true, message: '' },
              {
                validator: (_, value) => {
                  if (!value || value.trim() === '') {
                    return Promise.reject(
                      new Error(isTiangongManager ? '请输入邮箱!' : '请输入名称!'),
                    );
                  }
                  if (value.trim().length > SHORT_TEXT) {
                    return Promise.reject(new Error(`上限字数为${SHORT_TEXT}个`));
                  }
                  // 如果是天工用户，验证邮箱格式
                  if (isTiangongManager) {
                    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                    if (!emailRegex.test(value.trim())) {
                      return Promise.reject(new Error('请输入正确的邮箱格式!'));
                    }
                  }
                  return Promise.resolve();
                },
              },
            ]}
          >
            <Input
              type={isTiangongManager ? 'email' : 'text'}
              placeholder={isTiangongManager ? '请输入邮箱' : '请输入名称'}
              className="!border-0 !bg-input-gray !text-base"
            />
          </Form.Item>
          {!isTiangongManager && (
            <Form.Item
              label="学/工号"
              name="user_id"
              rules={[
                { required: true, message: '' },
                {
                  validator: (_, value) => {
                    if (!value || value.trim() === '') {
                      return Promise.reject('请输入学/工号!');
                    }
                    if (value.trim().length > SHORT_TEXT) {
                      return Promise.reject(`上限字数为${SHORT_TEXT}个`);
                    }
                    return Promise.resolve();
                  },
                },
              ]}
            >
              <Input placeholder="请输入学/工号" className="!border-0 !bg-input-gray !text-base" />
            </Form.Item>
          )}
          {updateOrEdit && isLocalAccount && (
            <Form.Item
              label="密码"
              name="password"
              rules={[
                { required: true, message: '' },
                {
                  validator: (_, value) => {
                    if (!value || value.trim() === '') {
                      return Promise.reject('请输入密码!');
                    }
                    if (value.trim().length > SHORT_TEXT) {
                      return Promise.reject(`上限字数为${SHORT_TEXT}个`);
                    }
                    return Promise.resolve();
                  },
                },
              ]}
            >
              <Input.Password
                placeholder="请输入密码"
                className="!border-0 !bg-input-gray !text-base"
              />
            </Form.Item>
          )}
          <Form.Item
            label="角色"
            name="role_code"
            rules={[{ required: true, message: '请选择角色类型!' }]}
          >
            <Select
              options={roleList}
              className="custom-select"
              fieldNames={{
                label: 'name',
                value: 'code',
              }}
            />
          </Form.Item>
          <Form.Item
            label="所属组织"
            name="group_id"
            rules={[{ required: true, message: '请选择你所属的组织!' }]}
          >
            <TreeSelect
              placeholder="请选择所属组织"
              treeData={tree}
              className="custom-select"
              treeDefaultExpandAll
              fieldNames={{
                label: 'name',
                value: 'id',
                children: 'children',
              }}
            />
          </Form.Item>
          <Form.Item
            label="账号启/停状态"
            name="status"
            style={{
              marginBottom: 0,
            }}
          >
            <Switch />
          </Form.Item>
        </Form>
      </ConfigProvider>
    </Modals>
  );
};

export default UpdateModal;
